package com.coconet.gas.jwt.service.impl;

import com.coconet.gas.dao.SysRoleMapper;
import com.coconet.gas.dao.SysUserMapper;
import com.coconet.gas.dao.SysUserRoleMapper;
import com.coconet.gas.exception.BaseException;
import com.coconet.gas.jwt.vo.JwtUser;
import com.coconet.gas.vo.dw.SysRole;
import com.coconet.gas.vo.dw.SysUser;
import com.coconet.gas.vo.dw.SysUserRole;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户验证方法
 *
 * @author hackyo Created on 2017/12/8 9:18.
 */
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

	@Resource
	private SysUserMapper membermapper;
	@Resource
	private SysUserRoleMapper memberrolemapper;
	@Resource
	private SysRoleMapper sysrolemapper;
	@Override
	public UserDetails loadUserByUsername(String username) {
		SysUser user = membermapper.selectByPrimaryKey(username);

		SysUserRole mr = new SysUserRole();
		mr.setUserId(username);
		List<SysUserRole> list_mr = memberrolemapper.select(mr);
		
		List<String> li = list_mr.stream().map(temp -> {
			SysRole record=new SysRole();
			record.setId(temp.getRoleId());
			return sysrolemapper.selectOne(record).getRoleName();		
		}).collect(Collectors.toList());
		list_mr.stream().forEach(temp -> {
			SysRole record=new SysRole();
			record.setId(temp.getRoleId());
			record= sysrolemapper.selectOne(record);
			if (record.getType()!=null&&record.getType()==1) {
				li.add("1");
			}
			
		});

		if (user == null) {
			throw new BaseException("用户不存在或账户密码错误!");
		} else {
			return new JwtUser(user.getUsername(), user.getPassword(),
					li.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
		}
	}
}